<template>
  <div>
    <div v-if="isViewMode" class="report-action">
      <el-button size="small" icon="el-icon-printer" :loading="printLoading" @click="printPage">
        打印
      </el-button>
      <el-button
        size="small"
        icon="el-icon-download"
        :loading="printLoading"
        @click="exportToExcel"
      >
        导出
      </el-button>
    </div>
    <div v-loading="loading" class="report-wrap">
      <div :id="printId">
        <div class="report-main">
          <table class="table">
            <tbody>
              <tr>
                <td class="border-0" colspan="10" data-font='{"sz": 16, "bold": true}'>
                  <h3 class="report-title">{{ fileName }}</h3>
                </td>
              </tr>
            </tbody>
          </table>
          <customer-related-view
            :related="latestRelatedView"
            :orgCorp="shareholderCorp"
            :isReport="true"
            :queryId="queryId"
            @save="judgeGetData"
            :view-mode="isViewMode"
          ></customer-related-view>
          <customer-target
            :queryId="queryId"
            :related="latestRelatedView"
            :view-mode="isViewMode"
            @save="judgeGetData"
          ></customer-target>
          <demand-funds
            :queryId="queryId"
            :related="latestRelatedView"
            @save="judgeGetData"
            :view-mode="isViewMode"
          ></demand-funds>
          <customer-project-type :related="latestRelatedView"></customer-project-type>
          <customer-industrial :queryId="queryId" :view-mode="isViewMode"></customer-industrial>
          <house-hold-view
            :queryId="queryId"
            @back="SetCommonData"
            :view-mode="isViewMode"
          ></house-hold-view>
          <share-holder-view
            :shareholders="shareholders"
            v-if="!isIndividual"
            :queryId="queryId"
            @success="getShareHolder"
            :view-mode="isViewMode"
          ></share-holder-view>
          <customer-credit-info
            :queryId="queryId"
            :enumSelectPerson="enumSelectPerson"
            :view-mode="isViewMode"
          ></customer-credit-info>
          <customer-finance-source
            :queryId="queryId"
            :view-mode="isViewMode"
          ></customer-finance-source>
          <customer-business-produce
            :queryId="queryId"
            :view-mode="isViewMode"
          ></customer-business-produce>
          <customer-insurance-order
            :queryId="queryId"
            :view-mode="isViewMode"
          ></customer-insurance-order>
          <customer-electricity-fee
            :queryId="queryId"
            :farm-id="farmId"
            :view-mode="isViewMode"
          ></customer-electricity-fee>
          <project-introduce
            :queryId="queryId"
            :related="latestRelatedView"
            :view-mode="isViewMode"
            @save="judgeGetData"
          ></project-introduce>
          <credit-aim
            :queryId="queryId"
            :related="latestRelatedView"
            :view-mode="isViewMode"
            @save="judgeGetData"
          ></credit-aim>
          <customer-finance-status
            :queryId="queryId"
            :related="latestRelatedView"
            :view-mode="isViewMode"
            @save="judgeGetData"
          ></customer-finance-status>
          <repayment-ability
            :queryId="queryId"
            :related="latestRelatedView"
            :view-mode="isViewMode"
            @save="judgeGetData"
          ></repayment-ability>
          <project-counter-guarantee
            :queryId="queryId"
            :related="latestRelatedView"
            :view-mode="isViewMode"
            @save="judgeGetData"
          ></project-counter-guarantee>
          <project-conclusion
            :queryId="queryId"
            :related="latestRelatedView"
            :view-mode="isViewMode"
            @save="judgeGetData"
          ></project-conclusion>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  printPage,
  exportToExcel,
  getResultData,
  getResultArray,
} from '@/gov/components/creditFile/index'
import CustomerRelatedView from '@/gov/components/creditFile/CustomerRelatedView'
import CustomerTarget from '@/gov/components/creditFile/CustomerTarget'
import DemandFunds from '@/gov/components/creditFile/DemandFunds'
import CustomerProjectType from '@/gov/components/creditFile/CustomerProjectType'
import CustomerIndustrial from '@/gov/components/creditFile/CustomerIndustrial'
import HouseHoldView from '@/gov/components/creditFile/HouseHoldView'
import ShareHolderView from '@/gov/components/creditFile/ShareHolderView'
import CustomerCreditInfo from '@/gov/components/creditFile/CustomerCreditInfo'
import CustomerFinanceSource from '@/gov/components/creditFile/CustomerFinanceSource'
import CustomerBusinessProduce from '@/gov/components/creditFile/CustomerBusinessProduce'
import CustomerInsuranceOrder from '@/gov/components/creditFile/CustomerInsuranceOrder'
import CustomerElectricityFee from '@/gov/components/creditFile/CustomerElectricityFee'
import ProjectIntroduce from '@/gov/components/creditFile/ProjectIntroduce'
import CreditAim from '@/gov/components/creditFile/CreditAim'
import CustomerFinanceStatus from '@/gov/components/creditFile/CustomerFinanceStatus'
import RepaymentAbility from '@/gov/components/creditFile/RepaymentAbility'
import ProjectCounterGuarantee from '@/gov/components/creditFile/ProjectCounterGuarantee'
import ProjectConclusion from '@/gov/components/creditFile/ProjectConclusion'
export default {
  components: {
    CustomerRelatedView,
    CustomerTarget,
    CustomerProjectType,
    CustomerIndustrial,
    DemandFunds,
    HouseHoldView,
    ShareHolderView,
    CustomerCreditInfo,
    CustomerFinanceSource,
    CustomerBusinessProduce,
    CustomerInsuranceOrder,
    CustomerElectricityFee,
    ProjectIntroduce,
    CreditAim,
    CustomerFinanceStatus,
    RepaymentAbility,
    ProjectCounterGuarantee,
    ProjectConclusion,
  },
  props: {
    queryId: {
      type: String,
      default: '',
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      saveLoading: false,
      printLoading: false,
      loading: false,
      latestRelatedView: {},
      tableName: 'customer_related',
      // 法人信息 股东信息 放入模块需请求两次
      shareholderCorp: {},
      shareholders: [],
      farmilyData: [],
      // 信用信息需要的下拉选择框 股东信息 家庭成员 法人
      enumSelectPerson: [],
      // 同步
      hasFinishSync: true,
      syncTimer: null,
    }
  },
  computed: {
    printId() {
      return `gov_crdit_${this.queryId}`
    },
    // 档案卡状态
    projectStatus() {
      // 0 未调查 1 已调查 2 调查中 3 已通过
      return +this.latestRelatedView.project_status
    },
    // 区县复核状态 0 待项目经理复核 1复审通过 2 复核不通过
    resStatus() {
      return +this.latestRelatedView.res_status
    },
    fileName() {
      return `${this.latestRelatedView.customer_name || ''}调查报告`
    },
    // 是否预审、受理通过
    isApproval() {
      // 0 未初审 1 已初审 2 已拒绝
      return +this.latestRelatedView.is_approval
    },

    isViewMode() {
      return this.viewMode
    },

    isIndividual() {
      return +this.latestRelatedView.customer_type === 2
    },
    farmId() {
      return this.latestRelatedView.customer_id
    },
  },
  watch: {
    queryId: {
      handler: function () {
        if (this.queryId) {
          this.getData()
          this.getShareHolder()
        }
      },
      immediate: true,
    },
    farmilyData: {
      handler: function () {
        this.getSelectData()
      },
      immediate: true,
    },
    shareholders: {
      handler: function () {
        this.getSelectData()
      },
      immediate: true,
    },
    shareholderCorp: {
      handler: function () {
        this.getSelectData()
      },
      immediate: true,
    },
  },
  mounted() {},
  created() {
    this.$once('hook:beforeDestroy', () => this.clearSync())
  },
  methods: {
    SetCommonData(data) {
      this.farmilyData = data
    },
    getSelectData() {
      this.enumSelectPerson = {}
      if (!this.latestRelatedView) {
        return
      }
      if (this.shareholderCorp) {
        this.enumSelectPerson[this.shareholderCorp.real_name] = this.shareholderCorp.real_name
      }
      this.shareholders.forEach(item => {
        if (!this.enumSelectPerson[item.real_name]) {
          this.enumSelectPerson[item.real_name] = item.real_name
        }
      })
      this.farmilyData.forEach(item => {
        if (!this.enumSelectPerson[item.real_name]) {
          this.enumSelectPerson[item.real_name] = item.real_name
        }
      })
      if (!this.enumSelectPerson[this.latestRelatedView.customer_name]) {
        this.enumSelectPerson[this.latestRelatedView.customer_name] =
          this.latestRelatedView.customer_name
      }
    },
    saveData() {
      const data = {
        project_status: 1,
      }
      if (+this.latestRelatedView.project_status === 0) {
        data.archive_complete_time = this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')
      }
      this.$utils
        .msgbox({
          message: '是否完成档案卡？',
          type: 'warning',
          beforeClose: () => this.updateRelated(data),
        })
        .then(res => {
          this.$message.success('档案卡已完成')
          this.$emit('success', res)
          this.getData()
        })
        .catch(() => this.$message.error(`提交失败，请重试！`))
    },
    updateRelated(data) {
      return new Promise((resolve, reject) => {
        this.$api
          .updateData(
            this.$serviceName,
            'customer_related',
            this.latestRelatedView.customer_related_id,
            data
          )
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    judgeGetData(val) {
      // val = false 修改法人 true 修改基本信息
      if (val) {
        this.getData(false)
      } else {
        this.getShareHolder(false)
      }
    },
    async getShareHolder(isloading = true) {
      this.loading = isloading
      const params = {
        'customer_related_id.eq': this.queryId,
      }
      await this.$api
        .getData(this.$serviceName, 'datum_customer_shareholder_view', params, { sh_rate: 'desc' })
        .then(res => {
          const data = getResultArray(res)
          this.shareholders = []
          for (const sh of data) {
            if (+sh.is_corp === 1) {
              this.shareholderCorp = { ...sh }
              if (+this.shareholderCorp.marriage_status === 0) {
                this.shareholderCorp.marriage_status = '2'
              }
            } else {
              // 如果sh_rate为字符串则页面显示不出来
              if (+sh.sh_rate > 0) {
                this.shareholders.push({ ...sh })
              }
            }
          }
        })
      this.loading = false
    },
    async getData(isloading = true) {
      this.loading = isloading
      const params = {
        'customer_related_id.eq': this.queryId,
      }
      await this.$api
        .getData(this.$serviceName, this.tableName, params, { create_time: 'desc' })
        .then(res => {
          this.latestRelatedView = getResultData(res)
          this.hasFinishSync = +(this.latestRelatedView.is_finish_sync || 1) === 1
          if (this.hasFinishSync) {
            this.clearSync()
          } else if (this.syncTimer === null) {
            this.syncTimer = setInterval(() => this.getData(false), 2000)
          }
        })
        .catch(() => {
          this.$message.error('请求项目基本信息失败')
        })
      this.loading = false
    },
    clearSync() {
      if (this.syncTimer === null) return
      clearInterval(this.syncTimer)
      this.syncTimer = null
    },
    printPage() {
      printPage(this.printId)
    },
    exportToExcel() {
      this.printLoading = true
      exportToExcel(this.printId, this.fileName)
        .catch(err => {
          const msg = (err && err.message) || ''
          this.$message.error(`导出失败，请重试！${msg}`)
        })
        .finally(() => {
          this.printLoading = false
        })
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/gov/components/creditFile/style.scss';
</style>
